package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;

import javax.swing.JLabel;
import javax.swing.JTextField;

import model.Adressbook;
import model.Contact;
import view.AddcontactView;
import view.ListView;

/**
 * 
 * @author Nelly-Kim TRAN
 * 
 * @param previousframe
 * 					keeps the previous frame in store to close it afterwards
 * @param firstname
 * 					to get the firstname of the contact to delete
 * @param lastname
 * 					to get the lastname of the contact to delete
 * 				
 *
 */

public class DeleteListener implements ActionListener{

	ListView previousframe;
	JTextField firstname;
	JTextField lastname;
	
	public DeleteListener(ListView f, JTextField firstname, JTextField lastname) {
		this.previousframe=f;
		this.firstname=firstname;
		this.lastname=lastname;
	}
	
	public void actionPerformed(ActionEvent e) {
		
		String firstname1=firstname.getText();
		String lastname1=lastname.getText();
		
		
		//kim,tran,paris,paris,4567567,345678,34567,345678,www.youtube.com,kim@gmail.com,kim@ece.fr,photo, family
		
		//deletion of the contact from the set
		Iterator i=Adressbook.contacts.iterator();
		while(i.hasNext()) {
			Contact c=(Contact)i.next();
			if( c.getFirstname().equals(firstname1) && c.getLastname().equals(lastname1) ) {
				i.remove();
			}
		}
		
	
		//deletion of the contact from the list
		try{
			
			File yourFile = new File("monfichier2.txt");
			yourFile.delete();
			File yourNewFile = new File("monfichier2.txt");
			yourNewFile.createNewFile(); 		
			
			PrintStream l_out = new PrintStream(new FileOutputStream("monfichier2.txt",true));	
			Iterator j=Adressbook.contacts.iterator();
			while(j.hasNext()) {
				Contact c=(Contact)j.next();
				l_out.print(c.getFirstname()+ ","); 
				l_out.print(c.getLastname()+","); 
				l_out.print(c.getHomeaddress()+","); 
				l_out.print(c.getCompanyaddress()+","); 
				l_out.print(c.getPersonalmobile()+","); 
				l_out.print(c.getPersonalhome()+","); 
				l_out.print(c.getProfessionnalmobile()+","); 
				l_out.print(c.getProfessionnaloffice()+","); 
				l_out.print(c.getHomepage()+","); 
				l_out.print(c.getPersonalemail()+","); 
				l_out.print(c.getProfessionalemail()+","); 
				l_out.print(c.getPhoto()+","); 
				l_out.print(c.getGroup()+"\r\n"); 
			}
	
			l_out.flush(); 
			l_out.close(); 
			l_out=null; 
		}
	
		catch (Exception exc) {System.out.println("problem with txt file");}
	
		previousframe.setVisible(false);
		previousframe.dispose();
		ListView f=new ListView();
		f.setVisible(true);

		
	}
}
